package com.zhouyer.study.controller;

import com.zhouyer.study.consts.RegisterResultStateEnum;
import com.zhouyer.study.dto.UserDTO;
import com.zhouyer.study.pojo.HttpResult;
import com.zhouyer.study.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 用户服务Controller
 *
 * @author zhouyao
 * @version 1.0
 * @date 2021/12/7 1:26 下午
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public HttpResult register(HttpServletResponse response, @RequestBody UserDTO userDTO) {
        Integer state = userService.register(response, userDTO);
        // 0:注册成功，-1：注册失败，1：用户已注册，2：验证码错误，3：验证码超时）
        if (state == 0) {
            return HttpResult.builder().code(RegisterResultStateEnum.REGIST_OK.getCode()).msg(RegisterResultStateEnum.REGIST_OK.getName()).build();
        }
        return HttpResult.builder().code(state).msg(RegisterResultStateEnum.getNameByCode(state)).build();
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public HttpResult login(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password) {
        String loginStatus = userService.login(response, email, password);
        if (StringUtils.isBlank(loginStatus)) {
            return HttpResult.builder().code(-1).msg("用户名或密码错误").build();
        }
        return HttpResult.builder().code(0).msg("登录成功").build();
    }

    @GetMapping("/info/{token}")
    public String userEmailInfo(@PathVariable("token") String token) {
        return userService.findEmailByToken(token);
    }

}
